<template>
  <div class="mgtBanks">
    <x-header v-show="!isWeChar">
      <div slot="default" class="common__header--title">{{pageTitle}}</div>
      <div @click="goBack" slot="overwrite-left"><img slot="icon" src="~assets/x3/ico/goback1.png" class="go-back"></div>
    </x-header>
    <!-- 银行卡列表 -->
    <div class="all_bank_list">
      <div class="row_bank" v-for="(item,index) in user.userDto.banks" :key="index" :style="item.backgroundColor | filter_color ">
        <div class="row_bank_top">
          <div class="text">
            <div class="name textTooMuch">&nbsp;{{item.fullName}}</div>
            <div class="type textTooMuch">&nbsp;{{item.typeName}}</div>
          </div>
          <div class="ico">
            <img :src="item.fullNamePinYin | filter_src" alt="">
          </div>
        </div>
        <div class="row_bank_bottom textTooMuch" :style="letter_spacing">&nbsp;{{item.number | filter_number}}</div>
        <div class="row_bank_option">
          <div class="default" v-if="item.isDefault == '1'">默认</div>
          <div class="setDefault" v-else @click="setDefault(item)">设为默认卡</div>
          <div class="unbundling" @click="unbundling(item)">解除绑定</div>
        </div>
        <!-- <div class="ico_background">
          <img src="~assets/x3/banks/jiansheyinhang.png" alt="">
        </div> -->
      </div>
      <div class="addCard" v-show="!isShowAdd && !isShowNext && bankLimit()" @click="showAdd">
        <span>+</span> 添加银行卡
      </div>
    </div>
    <!-- 添加银行卡 -->
    <div v-show="isShowAdd">
      <div class="addCard_notices">银行卡主姓名与实名认证姓名必须一致</div>
      <div class="all_banks">
        <x-input :value="user.userDto.userName" readonly>
          <span slot="label">持卡人：&nbsp;&nbsp;</span>
        </x-input>
        <x-input type="tel" v-model="bankNumber" placeholder="请输入银行卡号" :min="StrLenth.bankNoMin" :max="StrLenth.bankNoMax" @on-change="bankInfoChange">
          <span slot="label">卡&nbsp;&nbsp;号&nbsp;：&nbsp;&nbsp;</span>
        </x-input>
        <x-input v-model="bankBranchName" placeholder="请输入开户银行名称" :min="2" :max="50" @on-change="bankInfoChange">
          <span slot="label">支行名称：&nbsp;&nbsp;</span>
        </x-input>

        <selector placeholder="请选择省份" v-model="provinceObj" title="支行所在省" :options="provinceList" @on-change="bankInfoChange"></selector>
        <selector placeholder="请选择市" v-model="cityObj" title="支行所在市" :options="cityList" @on-change="bankInfoChange"></selector>
      </div>
      <x-button text="下一步" @click.native="submitAdd" type="primary" :disabled="isNext" class="mgtIdNumber_process_btn"></x-button>
    </div>
    <!-- 银行卡预留手机验证 -->
    <div v-show="isShowNext">
      <div class="addCard_notices">手机号为银行预留手机号</div>
      <div class="all_banks">

        <selector placeholder="请选择类型" v-model="bankName" title="卡类型" :options="bankNameList"></selector>

        <!-- <x-input class="bank_full_name" :value="bankName | filter_name" readonly>
          <img slot="label" style="padding-right:10px;display:block;" src="~assets/x3/ico/icon-card.png" width="18">
        </x-input> -->
        <x-input type="tel" :max="StrLenth.mobile" v-model="mobile" placeholder="请输入银行预留手机号" :disabled="isSendOk">
          <img slot="label" style="padding-right:10px;display:block;" src="~assets/x3/ico/ico-input-linkMobile.png" width="18">
        </x-input>
        <x-input type="tel" :max="StrLenth.sms" v-model="mobileCode" placeholder="请输入短信验证码">
          <img slot="label" style="padding-right:10px;padding-top:5px;display:block;" src="~assets/x3/ico/ico-input-Mcode.png" width="18">
          <x-button action-type="button" slot="right" mini class="linkMobileCode" @click.native="sendSmsCode" :text="sendBtnText" :disabled="isSendOk"></x-button>
        </x-input>
      </div>
      <x-button text="确认" @click.native="submitNext" type="primary" class="mgtIdNumber_process_btn"></x-button>
    </div>
    <!-- 提示信息 -->
    <toast v-model="showToast" type="warn">{{showToastText}}</toast>
  </div>
</template>
<script>
import { XHeader, XInput, XButton, Badge, Alert, AlertPlugin, Confirm, Toast, Selector } from "vux";
import { RouteUrl, Mutations, StrLenth } from "src/common/const";
import { RequestUrl } from "src/common/url";
import { mapState } from "vuex";
import Validation from "src/common/util/validation";
import { AreaList } from "src/js/cascadeArea";

export default {
  components: { XHeader, XInput, XButton, Badge, Alert, AlertPlugin, Confirm, Toast, Selector },
  computed: mapState(["user", "isWeChar"]),
  data() {
    return {
      StrLenth: {}, //字符长度常量
      letter_spacing: "letter-spacing: 4px;",//银行卡号文字间距和文字大小
      pageTitle: "银行卡",//页面标题名称
      showToastText: "", //提示信息
      showToast: false, //是否提示
      //第一步添加--------------
      isShowAdd: false,//是否显示添加银行卡界面
      isNext: true,//是否禁用点击下一步
      bankNumber: "",//输入的银行卡号
      bankBranchName: "",//开户支行名称

      bankName: null,//银行全称
      bankNameList: [],//银行卡名称列表
      provinceObj: null,//开户行所在省
      cityObj: null,//开户行所在市
      provinceList: [],
      cityList: [],

      //第二步提交--------------
      isShowNext: false,//是否显示手机验证界面
      mobile: "",//银行预留手机号
      mobileCode: "", //验证码
      isSendOk: false, //发送按钮是否禁用
      sendBtnText: "获取验证码", //发送按钮文本内容
    };
  },
  filters: {
    //根据返回的颜色值设置银行卡选项背景颜色
    filter_color(val) {
      let defaultVal = "background-color: ";
      if (typeof (val) == 'undefined' || val == undefined || val == null) {
        return defaultVal + "#2e68aa;box-shadow: 0px 1px 3px 1px gray;";
      }
      return defaultVal + val + ";box-shadow: 0px 1px 3px 1px " + val + ";";
      // return defaultVal + val + ";box-shadow: 0px 1px 3px 1px " + val + ";";
    },
    //根据拼音匹配图片地址
    filter_src(val) {
      if (typeof (val) == 'undefined' || val == undefined || val == null) {
        return "upload/assets/x3/banks/other.png";
      }
      return "upload/assets/x3/banks/" + val + ".png";
    },
    //字符超长时截取
    filter_name(val) {
      return (typeof (val) != 'undefined' && val.length > 15) ? val.substring(0, 15) + "……" : val;
    },
    //格式化输入的银行卡号
    filter_number(val) {
      if (typeof (val) != 'undefined' && val.length > 4) {
        return "**** **** **** " + val.substring(val.length - 4, val.length);
      }
      return val
    }
  },
  watch: {
    provinceObj(cur, old) {
      //当前选中省份已更换
      this.cityList = [];
      for (let i = 0; i < cur.city.length; i++) {
        let city = cur.city[i];
        let obj = { key: city, value: city.name };
        this.cityList.push(obj);//添加市
      }
    }
  },
  methods: {
    //返回
    goBack() {
      this.$common.goBackUrl(this, RouteUrl.ACCOUNT);
    },
    bankLimit() {
      let len = 0;
      if (Validation.isNotEmpty(this.user.userDto.banks) && this.user.userDto.banks.length > 0) {
        len = this.user.userDto.banks.length;
      }
      return len > 0 ? false : true;
    },
    //设置默认银行卡
    setDefault(item) {
      let _this = this;
      _this.$vux.confirm.show({
        content: "确认设置为默认", //显示内容
        showInput: false, //是否显示input
        confirmText: "确认",
        cancelText: "取消",
        onCancel() { ; },
        onConfirm() {
          let data = {
            TYPE: "FORM",
            userCode: _this.user.userDto.userCode,
            bankId: item.id,
            number: item.number
          }
          _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, true);
          _this.$http.post(RequestUrl.UPDATE_BANK_DEFAULT, data).then(function (res) {
            _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, false);
            if (res.state != 0) {
              _this.showToastText = res.result; _this.showToast = true; return;
            }
            //刷新银行卡列表
            _this.$common.storeCommit(_this, Mutations.REFRESH_BANK_LIST, res.result);
          });
        }
      });
    },
    //解除银行卡
    unbundling(item) {
      let _this = this;
      _this.$vux.confirm.show({
        content: "确认解除该银行卡", //显示内容
        showInput: false, //是否显示input
        confirmText: "确认",
        cancelText: "取消",
        onCancel() { ; },
        onConfirm() {
          let data = {
            TYPE: "FORM",
            userCode: _this.user.userDto.userCode,
            bankId: item.id,
            number: item.number
          }
          _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, true);
          _this.$http.post(RequestUrl.UPDATE_BANK_UNBUNDLING, data).then(function (res) {
            _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, false);
            if (res.state != 0) {
              _this.showToastText = res.result; _this.showToast = true; return;
            }
            //刷新银行卡列表
            _this.$common.storeCommit(_this, Mutations.REFRESH_BANK_LIST, res.result);

            //3s后自动或关闭窗口跳转到登录
            let showTime = setTimeout(() => {
              _this.$vux.alert.hide();
              _this.$common.goUrl(_this, RouteUrl.MGT_BANKS);
            }, 3000);
            //提示信息
            _this.$vux.alert.show({
              content: _this.$common.alertMsg("成功解绑:" + item.fullName, "green;"),
              buttonText: "确认",
              onHide() {
                clearTimeout(showTime);
                _this.$common.goUrl(_this, RouteUrl.MGT_BANKS);
              }
            });
          });
        }
      });
    },
    //显示添加银行卡界面
    showAdd() {
      this.isShowAdd = true;
    },
    //更改卡和支行名称时格式化卡号并校验支行名称决定启用或禁用下一步按钮
    bankInfoChange() {
      this.bankNumber = this.bankNumber.replace(/\s/g, '').replace(/(\d{4})(?=\d)/g, "$1 ");
      if (this.$common.isNotEmpty(this.bankNumber) && this.$common.isNotEmpty(this.bankBranchName) && this.bankNumber.length >= StrLenth.bankNoMin && this.bankBranchName.length >= 2 && this.bankBranchName.length <= 50 && this.$common.isNotEmpty(this.provinceObj) && this.$common.isNotEmpty(this.cityObj)) {
        //false = 解禁下一步按钮
        this.isNext = false;
      } else {
        //禁用下一步按钮
        this.isNext = true;
      }
    },
    //银行卡添加校验
    submitAdd() {
      if (this.$common.isEmpty(this.bankNumber)) {
        this.showToastText = "银行卡号不能为空"; this.showToast = true; return;
      }
      if (!(this.bankNumber.length == StrLenth.bankNoMin || this.bankNumber.length == StrLenth.bankNoMax)) {
        this.showToastText = "银行卡号必须为16或19位"; this.showToast = true; return;
      }
      if (this.$common.isEmpty(this.bankBranchName)) {
        this.showToastText = "支行名称不能为空"; this.showToast = true; return;
      }
      if (!(this.bankBranchName.length >= 2 && this.bankBranchName.length <= 50) || this.bankBranchName.indexOf("行") < 0) {
        this.showToastText = "请填写2-50位有效支行名称"; this.showToast = true; return;
      }
      let data = {
        TYPE: "FORM",
        userCode: this.user.userDto.userCode,
        userName: this.user.userDto.userName,
        bankNumber: this.bankNumber,
        province: this.provinceObj.name,//开户行所在省
        city: this.cityObj.name,//开户行所在市
        bankBranchName: this.bankBranchName
      }
      let _this = this;
      this.$common.storeCommit(this, Mutations.UPDATE_LOADING_STATUS, true);
      this.$http.post(RequestUrl.FIND_BANK_NO_OF_BINDING, data).then(function (res) {
        _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, false);
        if (res.state != 0) {
          _this.showToastText = res.result; _this.showToast = true; return;
        }
        let curBankName = res.result.bank.fullName;//当前自动获取的银行卡名称
        //银行名称列表
        let lists = res.result.bankNameList;
        for (let i = 0; i < lists.length; i++) {
          //列表单项值
          let obj = { key: lists[i], value: lists[i] };
          if (curBankName == obj.key) {
            //设置当前自动获取的银行卡名称
            _this.bankName = obj.key;
          }
          _this.bankNameList.push(obj);
        }
        _this.isShowNext = true;//显示下一步界面
        _this.isShowAdd = false;//隐藏添加界面
      });
    },
    // 发送验证码
    sendSmsCode() {
      /**
       * 发送验证码,返回data.msg=信息,data.state=0表示成功
       * isSendOk,true=禁用(disabled=true)
       * sendBtnText,验证码按钮文本显示内容
       */
      this.$common.sendSMS(this, this.mobile, null, this.isSendOk, "添加银行卡");
    },
    //提交下一步
    submitNext() {
      let data = {
        TYPE: "FORM",
        userCode: this.user.userDto.userCode,
        bankName: this.bankName,
        bankNumber: this.bankNumber,
        mobileCode: this.mobileCode,
        mobile: this.mobile
      };
      if (Validation.isEmpty(this.bankName)) {
        this.showToastText = "请选择银行卡类型"; this.showToast = true; return;
      }
      //校验-手机号
      let msg = Validation.isPhone11(data.mobile);
      if (msg != null) {
        this.showToastText = msg; this.showToast = true; return;
      }
      //校验-手机验证码
      msg = Validation.isSmsCode(data.mobileCode);
      if (msg != null) {
        this.showToastText = msg; this.showToast = true; return;
      }
      let _this = this;
      //请求
      _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, true);
      _this.$http.post(RequestUrl.UPDATE_BANK_OF_BINDING, data).then(function (res) {
        _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, false);
        if (res.state != 0) {
          _this.showToastText = res.result; _this.showToast = true; return;
        }
        //保存USER_INFO信息
        _this.$common.storeCommit(_this, Mutations.SAVE_USER_INFO, res.result);
        //刷新银行卡列表
        // _this.$common.storeCommit(_this, Mutations.REFRESH_BANK_LIST, res.result.banks);

        //3s后自动或关闭窗口跳转到登录
        let showTime = setTimeout(() => {
          _this.$vux.alert.hide();
          _this.$common.goUrl(_this, RouteUrl.MGT_BANKS);
        }, 3000);
        //提示信息
        _this.$vux.alert.show({
          content: _this.$common.alertMsg("成功绑定:" + data.bankName, "green;"),
          buttonText: "确认",
          onHide() {
            clearTimeout(showTime);
            _this.$common.goUrl(_this, RouteUrl.MGT_BANKS);
          }
        });

        _this.isShowNext = false;//显示下一步界面
      });
    },
    //初始化当前页面信息
    initPage() {
      //清除验证码倒计时
      this.$common.clearTimeOutForSms();
      if (!this.user.isLogin) {
        //未登录
        this.$common.goUrl(this, RouteUrl.LOGIN);
        return;
      }
      // this.mobile = this.user.userDto.mobile;//银行预留手机要
      if (!Validation.isChName(this.user.userDto.userName) || !Validation.isIdNumber(this.user.userDto.idNumber)) {
        //未实名的请先实名
        this.$common.goUrl(this, RouteUrl.MGT_IDNUMBER);
      }
      if (this.$common.isEmpty(this.user.banks) || this.user.banks.length < 1) {
        //查询银行卡列表
        let data = { _this: this, userCode: this.user.userDto.userCode };
        this.$common.storeCommit(this, Mutations.FIND_BANK_LIST, data);
      }
      // let w = document.body.clientWidth;//网页可见区域宽
      let inch = Validation.geInchByScreen();//根据屏幕分辨率获取英寸
      if (inch >= 5.5) {//iphone_plus
        this.letter_spacing = "letter-spacing: 7px;";
      } else if (inch >= 5.0 && inch < 5.5) {
        this.letter_spacing = "letter-spacing: 5px;";
      } else if (inch > 4.0 && inch < 5.0) {//iphone6
        this.letter_spacing = "letter-spacing: 5px;";
      } else {//iphone5,w < 350
        this.letter_spacing = "letter-spacing: 4px;";
      }
      //加载开户行所用的省份
      for (let i = 0; i < AreaList.length; i++) {
        let province = AreaList[i];
        let obj = { key: province, value: province.name };
        this.provinceList.push(obj);
      }
    }
  },
  mounted() {
    this.StrLenth = StrLenth; //字符长度常量
    document.title = this.pageTitle;
    this.$init.subPageInit(this);
    //初始化当前页面信息
    this.initPage();
  }
};
</script>
<style lang="scss" scoped>
.textTooMuch {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.mgtBanks {
  padding-bottom: 100px;
}
.all_bank_list {
  // width: 100%;
  height: auto;
  padding-top: 23px;
  border-radius: 5px;
  padding-left: 10px;
  padding-right: 10px;
  span {
    font-size: 14px;
  }
  .weui-cell {
    border-top: 1px solid #efefef;
  }
  .weui-cell:before {
    border-top: 0px;
  }
  //单张银行卡
  .row_bank {
    width: 100%;
    /* height: 120px; */
    padding: 10px 0px;
    border-radius: 5px;
    margin: -10px 0px;
    color: white;
    .row_bank_top {
      height: 50px;
      margin-left: 20px;
      //文字
      .text {
        float: left;
        width: 70%;
        height: 100%;
        .name {
          font-size: 18px;
        }
        .type {
          font-size: 14px;
        }
      }
      //图标
      .ico {
        position: relative;
        z-index: 1;
        float: left;
        width: 40px;
        height: 40px;
        background-color: white;
        border-radius: 50px;
        img {
          display: block;
          width: 32px;
          height: 32px;
          margin: 4px auto;
        }
      }
    }
    .row_bank_bottom {
      clear: both;
      width: 90%;
      font-size: 22px;
      letter-spacing: 4px;
      margin-left: 16px;
      font-weight: bolder;
      font-family: Agency FB;
    }
    //默认银行卡
    .row_bank_option {
      width: 86%;
      height: 30px;
      margin: 0px auto;
      // text-align: center;
      // padding-right: 50px;
      // padding: 10px 50px 0px 0px;
      // border-top: 1px solid #899090;
      .unbundling {
        float: left;
        width: 80px;
        height: 22px;
        line-height: 22px;
        color: #ebedf4;
        font-size: 12px;
      }
      .default {
        float: left;
        width: 80px;
        height: 22px;
        line-height: 22px;
        color: #ebedf4;
        font-size: 12px;
      }
      .setDefault {
        float: left;
        width: 80px;
        height: 22px;
        line-height: 22px;
        color: white;
        // border: 1px solid #99a7aa;
        font-size: 12px;
      }
    }
    //背景图
    .ico_background {
      z-index: 0;
      width: 100%;
      height: 100%;
      position: relative;
      img {
        z-index: 0;
        display: block;
        position: absolute;
        top: -5px;
        right: 20%;
      }
    }
  }
  //添加银行卡
  .addCard {
    color: gray;
    font-size: 18px;
    text-align: center;
    line-height: 30px;
    padding: 20px;
    span {
      font-size: 25px;
    }
  }
}
//input区域
.all_banks {
  margin: 15px auto;
  width: 95%;
  height: auto;
  border-radius: 5px;
  background-color: white;
  span {
    font-size: 14px;
  }
  .weui-cell {
    border-top: 1px solid #efefef;
  }
  .weui-cell:before {
    border-top: 0px;
  }
}
.addCard_notices {
  margin: 25px 0px 0px 0px;
  width: 95%;
  height: auto;
  color: gray;
  padding-left: 25px;
  font-size: 14px;
}

//图形码
.img__code {
  width: 80px;
  height: 31px;
  margin-left: 3px;
  vertical-align: middle;
}

//换一张图形码
.img__code--change {
  margin-left: 3px;
  vertical-align: middle;
  font-size: 14px;
}

//获取验证码按钮
.linkMobileCode {
  padding: 0px;
  width: 80px;
  height: 28px;
  line-height: 28px;
  font-size: 12px;
  color: #C8161D;
  border: 1px solid #C8161D;
  background-color: white;
}

//提交按钮
.mgtIdNumber_process_btn {
  width: 95%;
  font-size: 20px;
  margin-top: 30px;
}

//错误信息
.mgtIdNumber_errorMsg {
  color: red;
  font-size: 14px;
  margin-left: 10px;
  height: 36px;
}

//弹窗信息
.weui-dialog__bd {
  height: 30px;
  line-height: 30px;
}

//修改默认按钮失效时背景颜色
.weui-btn_disabled.weui-btn_primary {
  background-color: #cfcfcf;
}
</style>
